<?php

namespace App\Repositories\Manage;

use App\Models\LouAddress;

class LouAddressRepository
{
    public function getList($filter = null, $pageNum = 1, $pageSize = 20)
    {
        $res = LouAddress::query()
            ->when(strlen($filter['pid']) > 0, function ($q) use ($filter) {
                return $q->where("pid", intval($filter['pid']));
            })
            ->when(!empty($filter['keywords']), function ($q) use ($filter) {
                return $q->where("title", "like", "%" . ($filter['keywords'] ?? "") . "%");
            })
            ->orderBy("sort", "asc")
            ->paginate($pageSize, ['id', 'title', 'type', 'pid', 'level', 'sort', 'status'], null, $pageNum)
            ->toArray();

        $res = filterPaginateData($res);
        foreach ($res['items'] as $k => &$v) {
            if ($v['level'] == 1) {
                $v['title'] = is_numeric($v['title']) ? ($v['title'] . '号楼') : $v['title'];
            } else if ($v['level'] == 2) {
                $v['title'] = is_numeric($v['title']) ? ($v['title'] . 'F') : $v['title'];
            }
        }

        return $res;
    }

    public function getOne(int $id = 0)
    {
        if (!$id)
            return null;

        return LouAddress::where("id", $id)->first();
    }


    public function saveOrUpdate($params = [], $id = 0)
    {
        $data['title'] = $params['title'] ?? "";
        $data['sort'] = $params['sort'] ?? 40;
        $data['pid'] = $params['pid'] ?? 0;
        $data['type'] = $params['type'] ?? 0;

        if (!$id && intval($params['pid'])) {
            $level = LouAddress::query()->where(['id' => $params['pid']])->value("level");
            $data['level'] = intval($level) ? (intval($level) + 1) : 1;

            if ($data['level'] > 4) {
                return false;
            }
        }

        if (intval($id)) {
            LouAddress::where("id", $id)->update($data);
            return $id;
        } else {
            $res = LouAddress::create($data);
            return $res['id'] ?? "";
        }
    }

    /**
     * 批量删除
     * @param null $ids
     */
    public function batchDelete($ids = null)
    {

        if (intval($ids)) {
            LouAddress::where(['id' => $ids])->delete();
        } else {
            LouAddress::whereIn("id", $ids)->delete();
        }

        return retSuc([], "删除成功");
    }

}
